import uuid

from django.http import JsonResponse

from myapp.elecmain import mysqlconnect
import requests


# 查询商家
def ordinary_merchants():
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            # 执行查询
            sql = "SELECT Merchant_id,Merchant_name,Address,Local_currency,My_profit from merchant"
            cursor.execute(sql)
            result = cursor.fetchall()
            print("查询的数据为:", result)
            return result
    except Exception as e:
        print("出现错误:", e)

ordinary_merchants()

# 删除商家
def delete_merchants(Merchant_id):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            # 执行删除操作
            sql = "DELETE FROM merchant WHERE Merchant_id = %s"
            affected_rows = cursor.execute(sql, (Merchant_id,))
            if affected_rows > 0:
                connect.commit()
                print("删除成功")
            else:
                print("未找到商家或删除失败")
    except Exception as e:
        print("出现错误:", e)


# 添加商家
def add_merchants(Merchant_name, Address, Local_currency):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            # 执行查询
            sql = "INSERT INTO merchant(Merchant_name,Address,Local_currency) values (%s, %s, %s)"
            cursor.execute(sql, (Merchant_name, Address, Local_currency))
            connect.commit()
            print("添加成功")
    except Exception as e:
        print("出现错误:", e)


# 设置商家代理
def merchant_agent(mer_id, name, level, original_id):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            sql = "UPDATE merchant SET Merchant_id= %s,Merchant_name= %s,Merchant_agent_hierarchy = %s where Merchant_id= %s"
            cursor.execute(sql, (mer_id, name, level, original_id))
            # 提交事务
            connect.commit()
            print("更改成功")
    except Exception as e:
        print("出现错误:", e)


# 添加门店
def add_store(Store_id, Store_name, Address, Longitude, Latitude):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            update_sql = """
                UPDATE store
                SET Store_name = %s, Address = %s, Longitude = %s, Latitude = %s
                WHERE Store_id = %s;
            """
            cursor.execute(update_sql, (Store_name, Address, Longitude, Latitude, Store_id))

            if cursor.rowcount == 0:
                insert_sql = """
                    INSERT INTO store (Store_id, Store_name, Address, Longitude, Latitude)
                    VALUES (%s, %s, %s, %s, %s);
                """
                cursor.execute(insert_sql, (Store_id, Store_name, Address, Longitude, Latitude))

            # 提交事务
            connect.commit()
            print("操作成功")
    except Exception as e:
        print("出现错误:", e)


# 查询门店
def get_store():
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            # 执行查询
            sql = "SELECT * from store"
            cursor.execute(sql)
            result = cursor.fetchall()
            print("查询的数据为:", result)
    except Exception as e:
        print("出现错误:", e)
    return result


# 删除门店
def delete_store(Store_id):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            # 执行删除操作
            sql = "DELETE FROM store WHERE Store_id = %s"
            affected_rows = cursor.execute(sql, (Store_id,))
            if affected_rows > 0:
                connect.commit()
                print("删除成功")
            else:
                print("未找到商家或删除失败")
    except Exception as e:
        print("出现错误:", e)


# 查找硬件
def query_hardware(Bind_merchant):
    data = []
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            if not Bind_merchant:
                raise ValueError("Bind_merchant 不能为空")  # 处理空列表的情况
            format_strings = ','.join(['%s'] * len(Bind_merchant))
            sql = f"SELECT * FROM hardware WHERE Bind_merchant IN ({format_strings})"
            cursor.execute(sql, Bind_merchant)
            # 提交事务
            connect.commit()
            data = cursor.fetchall()
            print("查找成功")
            for row in data:
                print("数据：", row)
    except Exception as e:
        print("出现错误:", e)
    return data


# 添加硬件
def add_hardware(Hardware_QR_code, Hardware_type, Bind_merchant, Store_id):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            sql = "INSERT INTO hardware (Hardware_QR_code,Hardware_type,Bind_merchant,Store_id)VALUES (%s,%s,%s,%s);"
            cursor.execute(sql, (Hardware_QR_code, Hardware_type, Bind_merchant, Store_id))
            # 提交事务
            connect.commit()
            print("添加成功")
    except Exception as e:
        print("出现错误:", e)


# 将硬件转移到我其他门店
def transfer_hardware(Store_name, Hardware_ID):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            sql = "UPDATE hardware SET Store_id = (SELECT Store_id FROM store WHERE Store_name = %s LIMIT 1) WHERE Hardware_ID = %s"
            cursor.execute(sql, (Store_name, Hardware_ID))
            # 提交事务
            connect.commit()
            print("修改成功")
    except Exception as e:
        print("出现错误:", e)


# 订单管理
def order_manage():
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            sql = "SELECT * FROM orders"
            cursor.execute(sql)
            result = cursor.fetchall()

        print("查询的数据为:", result)
    except Exception as e:
        print("出现错误:", e)
    return result


# 套餐管理
# 查找
def Service_find():
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            sql = "SELECT * FROM Service"
            cursor.execute(sql)
            result = cursor.fetchall()
        print("查询的数据为:", result)
    except Exception as e:
        print("出现错误:", e)
    return result


# 添加
def add_Service(Service_id, Service, Price, Hardware_type, Store_id):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            sql = "INSERT INTO Service (Service_id,Hardware_type, Service, Price, Store_id )VALUES (%s,%s,%s,%s,%s);"
            cursor.execute(sql, (Service_id, Hardware_type, Service, Price, Store_id))
            # 提交事务
            connect.commit()
            print("添加成功")
    except Exception as e:
        print("出现错误:", e)


# 删除
def delete_service(service_id):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            # 执行删除操作
            sql = "DELETE FROM Service WHERE Service_id = %s"
            affected_rows = cursor.execute(sql, (service_id,))
            if affected_rows > 0:
                connect.commit()
                print("删除成功")
            else:
                print("未找到服务套餐或删除失败")
    except Exception as e:
        print("出现错误:", e)


# 修改
def modify_service(Service_id, Hardware_type, Service, Price, Store_id):
    connect = mysqlconnect.mysql_connect()
    try:
        with connect.cursor() as cursor:
            # 执行删除操作
            sql = "UPDATE Service SET Service_id = %s,Hardware_type= %s, Service= %s, Price= %s, Store_id = %s WHERE Service_id = %s"
            cursor.execute(sql, (Service_id, Hardware_type, Service, Price, Store_id))
            connect.commit()
            print("更改成功")
    except Exception as e:
        print("出现错误:", e)


# 用户注册
def register(user_id, userName, password):
    # java注册接口
    java_service_url = 'http://ec2-3-141-17-122.us-east-2.compute.amazonaws.com/trAssetUser/insert'

    # 构造请求体
    payload = {
        "externalUserInfo": "string",
        "externalUserName": "string",
        "id": user_id,
        "password": password,
        "status": 0,
        "userName": userName
    }
    return call_java_service(java_service_url, payload)


# 查看相应
def call_java_service(url, payload):
    try:
        # 发起 HTTP 请求到 Java 服务
        response = requests.post(url, json=payload)
        # 检查 Java 服务的响应
        if response.status_code == 200:
            return JsonResponse({'status': 'success', 'message': response.json()})
        else:
            return JsonResponse({'status': 'error', 'message': 'Java service error'}, status=response.status_code)
    except requests.RequestException as e:
        # 处理请求异常
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)


# 修改密码
def modify(user_id, userName, password):
    java_service_url = 'http://ec2-3-141-17-122.us-east-2.compute.amazonaws.com/trAssetUser/updata'
    payload = {
        "externalUserInfo": "string",
        "externalUserName": "string",
        "id": user_id,
        "password": password,
        "status": 0,
        "userName": userName
    }
    return call_java_service(java_service_url, payload)


# 删除用户
def remove_user(user_id):
    java_service_url = 'http://ec2-3-141-17-122.us-east-2.compute.amazonaws.com/trAssetUser/delete'
    payload = {
        "id": user_id,
    }
    return call_java_service(java_service_url, payload)


# 调用支付接口
def pay_payment(method, icon, ids, money, userId, moneyType):
    # Java 服务的支付完成接口 URL
    java_service_url = f'http://ec2-3-141-17-122.us-east-2.compute.amazonaws.com/pay/{method}'
    # 生成一个唯一的 UUID
    # unique_id = str(uuid.uuid4())
    unique_id = ids
    # 准备请求体数据
    payloads = {
        "icon": icon,
        "id": unique_id,
        "money": money,
        "moneyType": moneyType,
        "userId": userId
    }
    try:
        # 发起 POST 请求到 Java 服务
        response = requests.post(java_service_url, json=payloads, headers={'Content-Type': 'application/json'})

        # 检查 Java 服务的响应
        if response.status_code == 200:
            return JsonResponse({'status': 'success', 'message': response.json()})
        else:
            return JsonResponse({'status': 'error', 'message': 'Java service error'}, status=response.status_code)
    except requests.RequestException as e:
        # 处理请求异常
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)


# PayPal 支付
def pay_paypal(icon, money, userId, moneyType):
    return pay_payment('paypal', icon, money, userId, moneyType)


# 微信支付
def pay_wx(icon, money, userId, moneyType):
    return pay_payment('wx', icon, money, userId, moneyType)


# 订单添加
def addpay(icon, ids, money,  userId, moneyType):
    return pay_payment('add', icon, money, ids, userId, moneyType)
